/**
 * 对话存储管理工具函数
 */
import { Message, SavedConversation } from '../../types/chat.ts';
import { ChatMessage } from '../aiApi.ts';

/**
 * 保存对话到本地存储
 * @param messages 当前消息列表
 * @param historyMessages 历史消息
 * @param chapter 当前章节
 * @returns 是否保存成功
 */
export const saveConversation = (
    messages: Message[],
    historyMessages: ChatMessage[],
    chapter: string = 'general'
): boolean => {
    try {
        const conversationData: SavedConversation = {
            id: Date.now().toString(),
            messages,
            historyMessages,
            timestamp: new Date().toISOString(),
            chapter,
            title: `与AI的对话 (${new Date().toLocaleString()})`
        };

        const savedConversations = JSON.parse(localStorage.getItem('aiConversations') || '[]');
        savedConversations.push(conversationData);
        localStorage.setItem('aiConversations', JSON.stringify(savedConversations));

        return true;
    } catch (error) {
        console.error('保存对话失败:', error);
        return false;
    }
};

/**
 * 加载所有保存的对话
 * @returns 保存的对话列表
 */
export const loadSavedConversations = (): SavedConversation[] => {
    try {
        return JSON.parse(localStorage.getItem('aiConversations') || '[]');
    } catch (error) {
        console.error('加载保存的对话失败:', error);
        return [];
    }
};

/**
 * 删除指定ID的对话
 * @param conversationId 要删除的对话ID
 * @returns 是否删除成功
 */
export const deleteConversation = (conversationId: string): boolean => {
    try {
        const savedConversations = loadSavedConversations();
        const updatedConversations = savedConversations.filter(
            item => item.id !== conversationId
        );
        localStorage.setItem('aiConversations', JSON.stringify(updatedConversations));
        return true;
    } catch (error) {
        console.error('删除对话失败:', error);
        return false;
    }
}; 